package com.interview.ujiuye;

import java.util.concurrent.TimeUnit;

class Bank {
    private static ThreadLocal<Integer> account = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 100;
        }
    };
    public int getAccount() {
        return account.get();
    }
    /**
     * 用同步方法实现
     * @param money
     */
    public  void save(int money) {
        try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
       account.set(account.get() + money);
    }

}

class NewThread implements Runnable {
    private Bank bank;
    public NewThread(Bank bank) {
        this.bank = bank;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            bank.save(10);
            System.out.println(Thread.currentThread().getName()+"账户余额为：" + bank.getAccount());
        }
    }
}
    /**
     * 线程同步的运用
     */
    public class SynchronizedThread {
        public static void main(String[] args) {
            Bank bank = new Bank();
            NewThread new_thread = new NewThread(bank);
            System.out.println("线程1");
            Thread thread1 = new Thread(new_thread);
            thread1.start();
            System.out.println("线程2");
            Thread thread2 = new Thread(new_thread);
            thread2.start();
        }
}